/**
 * 
 */
package org.springframework.orm.ibatis.ext.ibatis230;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Properties;

import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import org.springframework.orm.ibatis.SqlMapClientFactoryBean;
import org.springframework.util.ObjectUtils;

import com.ibatis.common.xml.NodeletException;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser;
import com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParserWithSpringForIbatis2;
import com.ibatis.sqlmap.engine.builder.xml.SqlMapParser;

/**
 * @author ljw
 *
 */
public class SqlMapClientFactoryBeanExt extends SqlMapClientFactoryBean {

	protected SqlMapClient buildSqlMapClient(
			Resource[] configLocations, Resource[] mappingLocations, Properties properties)
			throws IOException {

		if (ObjectUtils.isEmpty(configLocations)) {
			throw new IllegalArgumentException("At least 1 'configLocation' entry is required");
		}

		SqlMapClient client = null;
		SqlMapConfigParserWithSpringForIbatis2 configParser = new SqlMapConfigParserWithSpringForIbatis2();
		for (int i = 0; i < configLocations.length; i++) {
			InputStream is = configLocations[i].getInputStream();
			try {
				client = configParser.parse(is, properties);
			}
			catch (RuntimeException ex) {
				throw new NestedIOException("Failed to parse config resource: " + configLocations[i], ex.getCause());
			}
		}

//		if (mappingLocations != null) {
//			SqlMapParser mapParser = SqlMapParserFactory.createSqlMapParser(configParser);
//			for (int i = 0; i < mappingLocations.length; i++) {
//				try {
//					mapParser.parse(mappingLocations[i].getInputStream());
//				}
//				catch (NodeletException ex) {
//					throw new NestedIOException("Failed to parse mapping resource: " + mappingLocations[i], ex);
//				}
//			}
//		}

		return client;
	}
}
